#! /usr/bin/python3
# -- coding: utf-8 --**
'''
下载最新的每日构建的 dayu200 镜像包。
默认下载到当前目录下。

python dl_dayu200.py
'''

import os
import sys
import json
import datetime
import requests
from urllib.request import urlretrieve

progress = int(0)

def download(url, path='./'):
    def reporthook(a, b, c):
        global progress
        if progress != int(a * b * 1000 / c):
            progress = int(a * b * 1000 / c)
            print(f"\rdownloading: {(a * b * 100 / c):5.1f}%", end="")
            sys.stdout.flush()

    file_name = os.path.basename(url)
    file_path = os.path.join(path, file_name)
    # 判断文件是否存在，不存在则下载
    if not os.path.isfile(file_path):
        print(f'Downloading from {url}')
        urlretrieve(url, file_path, reporthook=reporthook)
        print(f'\nfile path: {file_path}')
    else:
        print('file already exists.')
    # 获取文件大小
    file_size = os.path.getsize(file_path)
    print(f'file size = {file_size/1024/1024:.2f} MB.')

if __name__ == '__main__':
    TIME_STEP = 12
    DOWNLOAD_PATH = r'D:\Resource\Downloads'
    # 获取时间区间
    now_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    last_12_hours = (datetime.datetime.now() + datetime.timedelta(hours=-TIME_STEP)).strftime('%Y%m%d%H%M%S')
    # url
    url = 'http://ci.openharmony.cn/api/ci-backend/ci-portal/v1/dailybuilds'
    post_obj = {
        'pageNum': 1, "pageSize":1000,
        'startTime':'', 'endTime': '',
        'projectName':'openharmony', 'branch': 'master',
        'component': '', 'deviceLevel': '',
        'hardwareBoard': '', 'buildStatus': 'success',
        'buildFaileReason': '', 'testResult': ''
    }
    post_obj['startTime'] = last_12_hours
    post_obj['endTime'] = now_time
    post_obj['branch'] = 'master'
    
    res = requests.post(url, data=post_obj)
    data = json.loads(res.text)
    
    last_dayu200_img_url = ''
    items = data['result']['dailyBuildVos']
    for i in items:
        if i['component'] == 'dayu200':
            last_dayu200_img_url = i['imgObsPath']
            break
    if last_dayu200_img_url == '':
        print(f'没有获取到过去{TIME_STEP}小时内，dayu200 的每日构建镜像包。')
        sys.exit(0)
    
    try:
        download(last_dayu200_img_url, DOWNLOAD_PATH)
    except BaseException as err:
        file_name = os.path.basename(last_dayu200_img_url)
        file_path = os.path.join(DOWNLOAD_PATH, last_dayu200_img_url)
        if os.path.exists(file_path):
            os.remove(file_path)
        print('下载失败。', err)
    pass